import { NativeModules, NativeEventEmitter, Platform } from 'react-native';

const { RND2d:rnd2d, RND2dPlayerManager } = NativeModules;
const eventEmitter = new NativeEventEmitter(rnd2d);
let instances = 0;
const init = async function(id){
    await rnd2d.init(id);
}

const hasListener = function(name, callback) {
    let cbi = eventEmitter.listeners(name).findIndex(cb => cb === callback);
    if(-1 != cbi){
        return true;
    }else{
        return false;
    }
}

class RND2d {
    constructor(){
        this._id = instances++;
        init(this._id);
    }

    on(name,callback){
        this.addEventListener(name, callback);
    }

    off(name,callback){
        this.removeEventListener(name, callback);
    }

    addEventListener(name,callback){
        let evtName = `${name}-${this._id}`;
        if(!hasListener(evtName, callback)){
            eventEmitter.addListener(evtName, callback);
        }
    }

    removeEventListener(name,callback){
        eventEmitter.removeListener(`${name}-${this._id}`, callback);
    }

    create(addr,username,password){
        return rnd2d.create(this._id, addr, username, password);
    }

    getSdp(){
        return rnd2d.getSdp(this._id);
    }

    getSdpBase64(){
        return rnd2d.getSdpBase64(this._id);
    }

    start(sdp, client){
        return rnd2d.start(this._id, sdp, client);
    }

    startBase64(sdp, client){
        return rnd2d.startBase64(this._id, sdp, client);
    }

    initRtpSocket(ip, vport, aport){
        return rnd2d.initRtpSocket(this._id, ip, vport, aport);
    }

    initAudio(options){
        return rnd2d.initAudio(this._id, options);
    }

    startAudio(){
        return rnd2d.startAudio(this._id);
    }

    stopAudio(){
        return rnd2d.stopAudio(this._id);
    }

    destroy(){
        return rnd2d.destroy(this._id);
    }

    setTimeout(timeout){
        return rnd2d.setTimeout(this._id, timeout);
    }

    setPeerSourceReportInterval(interval){
        return rnd2d.setPeerSourceReportInterval(this._id, interval);
    }

    bindPlayer(){
        return rnd2d.bindPlayer(this._id);
    }

    play(){
        if('ios' == Platform.OS){
            return RND2dPlayerManager.play();
        }else{
            return rnd2d.play(this._id);
        }
    }

    stop(){
        if('ios' == Platform.OS){
            return RND2dPlayerManager.stop();
        }else{
            return rnd2d.stop(this._id);
        }
    }

    mute(muted){
        if('ios' == Platform.OS){
            return RND2dPlayerManager.mute(muted);
        }else{
            return rnd2d.mute(this._id,muted);
        }
    }

    takeSnapshot(path){
        if('ios' == Platform.OS){
            return RND2dPlayerManager.takeSnapshot(path);
        }else{
            return rnd2d.takeSnapshot(this._id,path);
        }
    }
}

const {
    D2D_ON_COMPLETE,
    D2D_ON_DATA,
} = rnd2d;

Object.assign(RND2d, {
    D2D_ON_COMPLETE,
    D2D_ON_DATA,
})

export default RND2d;